package main

import (
	"errors"
	"fmt"
	"time"

	md "gitee.com/countpoison/youbei/models"
	_ "gitee.com/countpoison/youbei/routers"
	"gitee.com/countpoison/youbei/utils"
	db "gitee.com/countpoison/youbei/utils/database"
	"gitee.com/countpoison/youbei/utils/jobs"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/toolbox"
)

func main() {
	md.Init("data")
	ts, err := md.All()
	if err != nil {
		panic(err)
	}
	if len(ts) > 0 {
		for _, ob := range ts {
			if ob.DBType == "mysql" {
				err = db.MysqlConnectTest(ob.Host, ob.Port, ob.DBname, ob.User, ob.Password, ob.Char)
			} else if ob.DBType == "mssql" {
				err = db.MssqlConnectTest(ob.Host, ob.DBname, ob.User, ob.Password)
			} else if ob.DBType == "sqlite" {
				err = db.SqliteConnectTest(ob.DBpath)
			} else if ob.DBType == "file" {
				bol, errs := utils.PathExists(ob.DBpath)
				err = errs
				if !bol {
					err = errors.New(ob.DBpath + " not found")
				}
			} else {
				fmt.Println("dbtype not found")
			}
			if err == nil && ob.Crontab != "" {
				toolbox.AddTask(ob.ID, toolbox.NewTask(ob.ID, ob.Crontab, jobs.Jobs(ob.ID)))
			}
		}
	}
	sshtasks := []md.SshTask{}
	if err := md.Localdb().Find(&sshtasks); err != nil {
		panic(err.Error())
	}
	for _, sshtask := range sshtasks {
		toolbox.AddTask(sshtask.ID, toolbox.NewTask(sshtask.ID, sshtask.Crontab, jobs.SshJobs(sshtask.ID)))
	}
	toolbox.AddTask("expireDelete", toolbox.NewTask("expireDelete", "0/10 * * * * *", func() error {
		tasks, err := md.All()
		if err != nil {
			return err
		}
		for _, v := range tasks {
			if v.Expire != 0 {
				now := time.Now().Unix()
				day := int64(v.Expire * 86400)
				jobs.ExpireDelete(v.ID, now-day)
			}
		}
		return nil
	}))
	toolbox.StartTask()

	beego.Run()

}
